// allocations.js
const api = require('../../utils/api.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    taskList: [],
    statusList: ['全部', '待完成', '已报工', '已完成'],
    statusIndex: 0,
    page: 1,
    limit: 10,
    hasMore: true,
    loading: false
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/allocations/allocations')) {
      return
    }
    
    this.loadTasks()
  },

  onShow() {
    this.refreshTasks()
  },

  // 加载任务列表
  loadTasks() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    const params = {
      page: this.data.page,
      limit: this.data.limit
    }
    
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusIndex - 1
    }
    
    api.getMyAllocations(params).then(res => {
      const newList = this.data.page === 1 ? res.data.list : [...this.data.taskList, ...res.data.list]
      
      this.setData({
        taskList: newList,
        hasMore: res.data.list.length === this.data.limit,
        loading: false
      })
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载任务失败:', err)
    })
  },

  // 刷新任务列表
  refreshTasks() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadTasks()
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadTasks()
    }
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: e.detail.value,
      page: 1,
      hasMore: true
    })
    this.loadTasks()
  },

  // 跳转到任务详情
  goToTaskDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/task-detail/task-detail?id=${id}`
    })
  },

  // 提交报工
  submitReport(e) {
    const id = e.currentTarget.dataset.id
    e.stopPropagation()
    
    wx.navigateTo({
      url: `/pages/submit-report/submit-report?allocation_id=${id}`
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshTasks()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMore()
  }
}) 